﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AhpilyServer
{
    /// <summary>
    /// 需要执行的方法
    /// </summary>
    public delegate void ExecuteDeleagte();
    /// <summary>
    /// 单线程池
    /// </summary>
    public class SingleExecute
    {
        public static SingleExecute Instance
        {
            get
            {
                lock (_instanceLock)
                {
                    if (_instance == null)
                    {
                        _instance = new SingleExecute();
                    }
                    return _instance;
                }
            }
        }

        /// <summary>
        /// 互斥锁
        /// </summary>
        public Mutex _mutex;

        private static SingleExecute _instance = null;
        private static readonly object _instanceLock = new object();

        private SingleExecute()
        {
            _mutex = new Mutex();
        }

        /// <summary>
        /// 单线程处理逻辑
        /// </summary>
        public void Exectue(ExecuteDeleagte executeDeleagte)
        {
            lock (this)
            {
                _mutex.WaitOne();
                executeDeleagte();
                _mutex.ReleaseMutex();
            }
        }
    }
}
